package middle;

import java.util.ArrayList;
import java.util.List;

public class Solution_241 {

    public static void main(String[] args) {
        Solution_241 model = new Solution_241();
        System.out.println(model.diffWaysToCompute("2-1-1"));
        System.out.println(model.diffWaysToCompute("2*3-4*5"));
        System.out.println(model.diffWaysToCompute("2"));
    }

    public List<Integer> diffWaysToCompute(String expression) {
        List<Character> fu_list = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if (c == '+' || c == '-' || c == '*') {
                fu_list.add(c);
                list.add(Integer.valueOf(builder.toString()));
                builder.delete(0, builder.length());
            } else {
                builder.append(c);
            }
        }
        list.add(Integer.valueOf(builder.toString()));
        return dps(0, list.size() - 1, fu_list, list);
    }

    private List<Integer> dps(int begin, int end, List<Character> fu_list, List<Integer> list) {
        List<Integer> rst = new ArrayList<>();
        if (begin == end) {
            rst.add(list.get(begin));
        } else {
            for (int i = begin; i < end; i++) {
                List<Integer> left = dps(begin, i, fu_list, list);
                List<Integer> right = dps(i + 1, end, fu_list, list);
                for (Integer leftNum : left) {
                    for (Integer rightNum : right) {
                        Character c = fu_list.get(i);
                        if (c == '+') {
                            rst.add(leftNum + rightNum);
                        } else if (c == '-') {
                            rst.add(leftNum - rightNum);
                        } else {
                            rst.add(leftNum * rightNum);
                        }
                    }
                }
            }
        }
        return rst;
    }
}
